//
//  MULXAuthHttpRequest.m
//  UniLoginSDK
//
//  Created by Song Xiaofeng on 13-12-13.
//  Copyright (c) 2013年 Mafengwo Inc. All rights reserved.
//

#import "MULXAuthHttpRequest.h"
#import "NSString+MULAdditions.h"
#import "STHTTPRequest.h"
#import "MULLoginManager.h"
#import "MULXAuthUtils.h"

extern NSString *__mul_consumerKey;
extern NSString *__mul_consumerSecret;
extern NSString *kLoginURL;

@interface MULXAuthHttpRequest()
{
    STHTTPRequest *_stHttpRequest;
}
@end

@implementation MULXAuthHttpRequest

+ (NSDictionary*)parseDicFromUrlQueryStr:(NSString*)queryStr withDecoding:(BOOL)decoding
{
    if (![queryStr isKindOfClass:[NSString class]] || queryStr.length == 0)
    {
        return nil;
    }
    
    NSMutableDictionary* dic = [NSMutableDictionary dictionaryWithCapacity:4];
    
    NSArray *resPairs = [queryStr componentsSeparatedByString:@"&"];
    for (NSString *keyValue in resPairs)
    {
        // @"key=" -> array:[@"key", @""]
        NSArray *pairs = [keyValue componentsSeparatedByString:@"="];
        if (pairs.count < 2)
        {
            continue;
        }
        NSString *value = [pairs objectAtIndex:1];
        if (value && [value isKindOfClass:[NSString class]])
        {
            if (decoding)
            {
                value = [value mul_urlEncode];
            }
            [dic setObject:value forKey:[pairs objectAtIndex:0]];
        }
    }
    return dic;
}
    
+ (NSString*)queryStringOfParameterDic:(NSDictionary*)unencodedDic
{
    if (unencodedDic)
    {
        __block NSMutableString *query = [[NSMutableString alloc] init];
        [unencodedDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if ([obj isKindOfClass:[NSString class]])
            {
                [query appendFormat:@"%@=%@&", key, [obj mul_urlEncode]];
            }
        }];
        if ([query length] > 0)
        {
            [query deleteCharactersInRange:NSMakeRange([query length] - 1, 1)];
        }
        return query;
    }
    return nil;
}

- (MULXAuthHttpRequest *)initWithURL:(NSURL *)theURL {
    
    if (self = [super init]) {
        _requestURL = theURL;
        
        NSString *queryStr = [_requestURL query];
        if (queryStr)
        {
            self.requestParamerts = [[NSMutableDictionary alloc] initWithDictionary:[MULXAuthHttpRequest parseDicFromUrlQueryStr:queryStr
                                                                                                                        withDecoding:NSUTF8StringEncoding]];
            // remove query string of _requestURL
            NSString *urlString = [_requestURL absoluteString];
            NSRange queryRange = [urlString rangeOfString:queryStr];
            if (queryRange.location != NSNotFound)
            {
                urlString = [urlString substringToIndex:queryRange.location - 1];
                
                _requestURL = [NSURL URLWithString:urlString];
            }
            
        }
        else
        {
            self.requestParamerts = [NSMutableDictionary dictionary];
        }
        
        self.HTTPMethod = kHttpGET;
    }
    
    return self;
}

+ (MULXAuthHttpRequest *)requestWithURL:(NSURL *)url;
{
    if (url == nil)
    {
        return nil;
    }
    
    return [[MULXAuthHttpRequest alloc] initWithURL:url];
}

+ (MULXAuthHttpRequest *)requestWithURLString:(NSString *)urlString;
{
    if (urlString == nil)
    {
        return nil;
    }
    
    return [[MULXAuthHttpRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
}

- (id)parseJsonData:(NSData*)data
{
    if (data)
    {
        return [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    }
    return nil;
}
    
- (void)requestDidFinished:(NSData*)responseData error:(NSError*)error
{
    if (self.xauthRequestDidCompleteBlock)
    {
        NSDictionary *parsedJson = nil;
        if (responseData && !error)
        {
            parsedJson = [self parseJsonData:responseData];
            
            
            // try to extract service error
            if (parsedJson)
            {
                NSLog(@"%@", parsedJson);
                int status = 1;
                if([parsedJson hasValueForKey:@"parameter"]) {
                    status = [[parsedJson valueForKey:@"parameter"] intValue];
                }
                if (status == 1)
                {
                }
                else
                {
                    NSString *errorInfo = [parsedJson valueForKey:@"data"];
                    error = [NSError errorWithDomain:kMULLoginErrorDomain code:-1 userInfo:@{kMULLoginErrorMessage: errorInfo}];
//                    error = [NSError errorWithDomain:kMULLoginErrorDomain code:status userInfo:@{kMULLoginErrorMessage: errorInfo}];
                }
            }
            else
            {
                error = [NSError errorWithDomain:kMULLoginErrorDomain code:-1 userInfo:@{kMULLoginErrorMessage: @"parse data error!"}];
            }

        }
        
        self.xauthRequestDidCompleteBlock(responseData, parsedJson, error);
    }
}
    
- (void)startAsynchronous;
{
//    NSString *token = nil;
//    NSString *tokenSecret = nil;
//    [MULLoginManager getSignatureToken:&token andSecret:&tokenSecret];

//    if ([kLoginURL isEqualToString:self.requestURL.absoluteString])
//    {
//        token = nil;
//        tokenSecret = nil;
//    }
    
    BOOL postMethodOrNot = [self.HTTPMethod isEqualToString:kHttpPOST];
//    NSMutableDictionary *publicArgumnetsDic = [NSMutableDictionary dictionary];
//    [MFWHttpParametersBuilder getPublicParameterFilledDictionary: publicArgumnetsDic];
//    [_requestParamerts addEntriesFromDictionary:publicArgumnetsDic];
//    NSMutableDictionary *signaturedParametes = [MULXAuthUtils signatureAuthParams:_requestParamerts
//                                                                       requestURL:_requestURL.absoluteString
//                                                              requestIsPostMethod:postMethodOrNot
//                                                              withAuthConsumerKey:__mul_consumerKey
//                                                                   consumerSecret:__mul_consumerSecret
//                                                                      accessToken:token
//                                                                      tokenSecret:tokenSecret];
    if (postMethodOrNot)
    {
        _stHttpRequest = [STHTTPRequest requestWithURL:_requestURL];
        _stHttpRequest.HTTPMethod = self.HTTPMethod;
        _stHttpRequest.POSTDictionary = _requestParamerts;
    }
    else
    {
        NSString *completeUrlString = [NSString stringWithFormat:@"%@?%@", _requestURL.absoluteString, [MULXAuthHttpRequest queryStringOfParameterDic:_requestParamerts]];
        NSURL *URL = [NSURL URLWithString:completeUrlString];
        NSAssert(URL, @"unvalidated NSURL with url string> %@", completeUrlString);

        _stHttpRequest = [STHTTPRequest requestWithURL:URL];
        _stHttpRequest.HTTPMethod = self.HTTPMethod;

    }
    
    __weak id wself = self;
    _stHttpRequest.completionDataBlock = ^(NSDictionary *headers, NSData *body) {
        __strong id sself = wself;
        if (sself)
        {
            [sself requestDidFinished:body error:nil];
        }
    };
    
    _stHttpRequest.errorBlock = ^(NSError *error) {
        __strong id sself = wself;
        if (sself)
        {
            [sself requestDidFinished:nil error:error];
        }
    };
    
    [_stHttpRequest startAsynchronous];
}

- (void)cancel;
{
    [_stHttpRequest cancel];
}

- (void)setHTTPMethod:(NSString *)HTTPMethod
{
    if ([kHttpGET isEqualToString:HTTPMethod] || [kHttpPOST isEqualToString:HTTPMethod])
    {
        _HTTPMethod = [HTTPMethod copy];
    }
    else
    {
        NSAssert(NO, @"None validate HTTP method: %@", HTTPMethod);
    }
}
    
#pragma mark - XAuth signature methods



@end
